<template>
  <div class="tree-container">
    <tree-node v-for="node in props.activedata" :key="node.id" :node="node" :level="0" :selected-node="selectedNode"
      @node-click="handleNodeClick" />
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import TreeNode from './treeact/TreeNode.vue'

const props = defineProps({
  activedata: {
    type: Array,
    default: () => []
  }
})
const injectedBtnactivindex = inject('btnactivindex')

// 定义树形数据
const treeData = ref([
  {
    id: 1,
    label: '一级 1',
    expanded: true,
    children: [
      {
        id: 4,
        label: '二级 1-1',
        expanded: false,
        children: [
          { id: 9, label: '三级 1-1-1', children: [] },
          { id: 10, label: '三级 1-1-2', children: [] }
        ]
      }
    ]
  },
  {
    id: 2,
    label: '一级 2',
    expanded: false,
    children: [
      {
        id: 5,
        label: '二级 2-1',
        children: []
      },
      {
        id: 6,
        label: '二级 2-2',
        children: []
      }
    ]
  },
  {
    id: 3,
    label: '一级 3',
    expanded: false,
    children: [
      {
        id: 7,
        label: '二级 3-1',
        children: []
      },
      {
        id: 8,
        label: '二级 3-2',
        children: []
      }
    ]
  }
])

// 定义选中的节点
const selectedNode = ref(null)

/**
 * 处理节点点击事件
 * @param {Object} node - 被点击的节点数据
 */
const handleNodeClick = (node) => {
  // console.log('点击的节点数据:', node)

  // 设置选中的节点
  selectedNode.value = node

  // 切换节点展开状态
  if (node.children && node.children.length > 0) {
    node.expanded = !node.expanded
  }
  // 调用祖组件提供的函数
  if (injectedBtnactivindex) {
    injectedBtnactivindex(node)
  }

}

onMounted(() => {
  // 组件挂载时的初始化逻辑
  console.log('自定义树形组件已挂载')
})
</script>

<style lang="less" scoped>
.tree-container {
  width: 290px;
  border-radius: 4px;
}
</style>